package com.ruoyi.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.lang.WeightRandom;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.http.Header;
import com.alibaba.fastjson.JSON;
import com.lzhpo.chatgpt.OpenAiException;
import com.lzhpo.chatgpt.OpenAiUrl;
import com.lzhpo.chatgpt.entity.chat.ChatCompletionRequest;
import com.lzhpo.chatgpt.entity.chat.ChatCompletionResponse;
import com.lzhpo.chatgpt.utils.JsonUtils;
import com.ruoyi.service.MicroSoftApiClient;
import com.ruoyi.util.OkHttpUtils;
import lombok.Cleanup;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.util.UriTemplateHandler;

import java.io.IOException;
import java.net.URI;
import java.util.Map;
import java.util.Objects;

import static com.lzhpo.chatgpt.OpenAiConstant.APPLICATION_JSON;
import static com.lzhpo.chatgpt.OpenAiConstant.BEARER;

/**
 * TODO
 *
 * @author chenchuan2
 * @date 2023-08-17 18:27:54
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@Service
public class MicroSoftApiClientImpl implements MicroSoftApiClient {

    @Autowired
    private OkHttpUtils okHttpUtils;

    @Autowired
    private final UriTemplateHandler uriTemplateHandler;

    private String url = "http://xdf-chat-saas.roombox.xdf.cn/xdfchat/v1/completions";

    private String appId = "common";

    private String secret = "aG4Y9dL8wboe73MO";

    @Override
    public ChatCompletionResponse chatCompletions(ChatCompletionRequest request){
        String completion = null;
        try {
            completion = okHttpUtils.doPostJson(
                    url,
                    JSON.toJSONString(request),
                    swHeaders().build()
            );
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JsonUtils.parse(completion, ChatCompletionResponse.class);
    }

    public Headers.Builder swHeaders() {
        Headers.Builder builder = new Headers.Builder();
        DateTime now = DateTime.now();
        String random = RandomStringUtils.randomAlphanumeric(16);
        String signature = MD5.create().digestHex(secret + random + now.getTime());
        builder.set("X-Roombox-App-Id", appId);
        builder.set("X-Roombox-Nonce", random);
        builder.set("X-Roombox-Timestamp", String.valueOf(now.getTime()));
        builder.set("X-Roombox-Signature", signature);
        return builder;
    }
}
